package com.guojiaming.shop.service;

import com.guojiaming.shop.bean.User;
import com.guojiaming.shop.bean.UserModifyPass;
import com.guojiaming.shop.bean.UserModity;
import com.guojiaming.shop.dao.UserMapper;
import com.guojiaming.shop.exception.DataModifyException;
import com.guojiaming.shop.exception.DataNotFindException;
import com.guojiaming.shop.exception.OperationException;
import com.guojiaming.shop.exception.VerificationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author vivo
 */
@Service
@Transactional(rollbackFor = {Exception.class})
public class UserService {

    @Resource
    private UserMapper userDao;


    public List<User> findAll() {
        return userDao.selectAll();
    }

    public User addUser(User user) {
        userDao.saveUser(user);
        return user;
    }

    public int deleteUser(Integer userId) {
        if (userDao.deleteUser(userId) <= 0) {
            throw new DataNotFindException();
        }
        return userId;
    }

    public User updateUser(UserModity userModity) {
        if (userModity.getUserId() == null) {
            throw new DataNotFindException("必须指定userId值");
        }
        if (userModity.getUserPass() != null) {
            throw new OperationException("不能在这里修改密码");
        }
        if (userDao.updateUser(User.getInstance(userModity)) <= 0) {
            throw new DataNotFindException("没有查询到该数据");
        }
        return userDao.selectUser(userModity.getUserId());
    }

    public User selectUser(Integer userId) {
        User user = userDao.selectUser(userId);
        if (user == null) {
            throw new DataNotFindException("没有查询到该数据");
        }
        return user;
    }

    public Boolean modifyPass(UserModifyPass userModifyPass) {
        User user = userDao.selectUser(userModifyPass.getUserId());
        if (user == null) {
            throw new DataNotFindException("没有查询到该数据");
        }
        if (!user.getUserPass().equals(userModifyPass.getOldPass())) {
            throw new VerificationException("密码验证失败");
        }
        user.setUserPass(userModifyPass.getNewPass());
        if (userDao.updateUser(user) <= 0) {
            throw new DataModifyException();
        }
        return true;
    }
}
